<?php
// +----------------------------------------------------------------------
// | astp [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Author 荒年 < 931274989@qq.com >
// +----------------------------------------------------------------------
// | Explain 获取access_token
// +----------------------------------------------------------------------
namespace app\yunmeng\service;

use think\Controller;
use think\facade\Config;
use app\yunmeng\service\HttpRequest;

class Accesstoken extends Controller
{
  // 获取Access_Token
  public function getAccessToken()
  {
    $http = new HttpRequest();
    //写入文件缓存
    $cacheAcc = Config::get('wewhat.APPID').'_cache.log';
    //判断文件是否存在，不存在则表示没有缓存
    //存在判断修改时间是否过了有效期，如果没有过，则不进行url网络请求
    if(is_file($cacheAcc) && filemtime($cacheAcc)+7200 > time()){
      return file_get_contents($cacheAcc);
    }
    $surl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s';
    $url = sprintf($surl,Config::get('wewhat.APPID'),Config::get('wewhat.SECRET'));
    // 发起get请求
    $json = $http->http_request($url);
    // 把json转化为数组
    $arr = json_decode($json,true);
    if(!empty($arr['access_token'])){
      $access_token = $arr['access_token'];
      //写入缓存
      file_put_contents($cacheAcc,$access_token);
      return $access_token;
    } else {
      return $arr['errmsg'];
    }
  }

}
?>